package goleetcode

import (
	"math"
	"sort"
)

func minimumDifference(nums []int, k int) int {
	n := len(nums)
	bitsMaxPos := make([]int, 31)
	for i := range bitsMaxPos {
		bitsMaxPos[i] = -1
	}

	res := math.MaxInt
	for i := 0; i < n; i++ {
		for j := 0; j <= 30; j++ {
			if nums[i] >> j & 1 == 1 {
				bitsMaxPos[j] = i
			}
		}

		posTObit := make([][2]int, 0)
		for j := 0; j <= 30; j++ {
			if bitsMaxPos[j] != -1 {
				posTObit = append(posTObit, [2]int{bitsMaxPos[j], j})
			}
		}
		sort.Slice(posTObit, func(i, j int) bool {
			return posTObit[i][0] > posTObit[j][0]
		})
		
		val := 0
		for j, p := 0, 0; j < len(posTObit); p = j {
			for j < len(posTObit) && posTObit[j][0] == posTObit[p][0] {
				val |= 1 << posTObit[j][1]
				j++
			}
			res = min(res, int(math.Abs(float64(val - k))))
		}
	}
	
	return res
}